package com.example.myapplication;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.app.ShareCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MainActivity extends AppCompatActivity {

    private static final int REQUEST_CODE_OPEN_DOCUMENT = 44;
    // 默认放在自己的应用下的files文件夹下，后面如果选取了excel文件会被改成那个excel文件所有的文件夹
    private File saveFile;
    private TextView logTextView;
    private InputStream is;

    private void goToChooseFile() {
        insertLog("尝试打开文件选择器");

        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*");
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        startActivityForResult(Intent.createChooser(intent, "选择文件"), REQUEST_CODE_OPEN_DOCUMENT);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        // 选择excel文件按钮
        Button selectExcelFileBtn = (Button) findViewById(R.id.select_excel_file_btn);
        selectExcelFileBtn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                goToChooseFile();
            }
        });


        // 打开保存的excel文件所在文件夹按钮
        Button openExcelFileSavedFolderBtn = (Button) findViewById(R.id.open_excel_file_saved_folder_btn);
        openExcelFileSavedFolderBtn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                openSavedExcelFileFolder();
            }
        });

        logTextView = (TextView) findViewById(R.id.logTextView);

        Button clearTextViewLogBtn = (Button) findViewById(R.id.clear_textView_log_btn);
        clearTextViewLogBtn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                logTextView.setText("");
            }
        });

        // 默认放在自己的应用下的files文件夹下，后面如果选取了excel文件会被改成那个excel文件所有的文件夹
        saveFile = new File(getExternalFilesDir(null), "new_excel.xls");
    }

    // 打开保存的excel文件所在文件夹
    private void openSavedExcelFileFolder() {


        Uri uri = FileProvider.getUriForFile(MainActivity.this, getPackageName() + ".fileprovider", saveFile);


        // 创建一个 Intent 对象，并设置 action 为 ACTION_SEND
        Intent shareIntent = ShareCompat.IntentBuilder.from(this)
                .setType("*/*")
                .setStream(uri)
                .getIntent()
                .setAction(Intent.ACTION_SEND)
                .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

        // 设置分享的标题
        shareIntent.putExtra(Intent.EXTRA_SUBJECT, "分享文件");
        // 启动分享的 Activity
        startActivity(Intent.createChooser(shareIntent, "分享文件到"));

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_CODE_OPEN_DOCUMENT && data != null) {
            Uri uri = data.getData();
            if (uri != null) {
                insertLog("选择了文件：" + uri.getPath());
                didGetFile(uri);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == 1) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 用户已经授予所请求的权限，可以在此处执行相关操作

                readExcelFile();
            } else {
                // 用户拒绝了所请求的权限，因此不能执行相关操作。
                // 您可以在此处弹出一个提示框或者启动一个适当的界面，以便用户能够手动授予所请求的权限
                insertError("没有获取访问文件的授权");
            }
        }
    }

    private void didGetFile(Uri uri) {
        // 这个方法很对 https://stackoverflow.com/questions/49704747/filenotfoundexception-open-failed-enoent-no-such-file-or-directory-while-uplo
        try {
            is = getContentResolver().openInputStream(uri);
        } catch (FileNotFoundException e) {
            insertError("获取文件的InputStream失败：" + e.getMessage());

        }
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);

            return;
        }
        readExcelFile();
    }

    private void readExcelFile() {
        insertLog("尝试打开excel文件");
        try {

            // 已经授予存储权限，在此处读取 Excel 文件
            HSSFWorkbook workbook = new HSSFWorkbook(is);
            HSSFSheet sheet = workbook.getSheetAt(0);

            int end = 40;
            // 目标内容类似于: 车站4，镇西邮政6，威远6，内江20，邱家嘴建行2，临江建行4，旅馆4
            // 目标内容是从哪一行开始填写的
            int targetContentCellStartRowNum = 3;
            // 目标内容在哪一列
            int targetContentCellColumnNum = 3;

            /// 异地交通费起步价
            double bigPrice = 10;
            // 异地交通费在哪一列
            int targetOtherPlacesTransportationCellColumnNum = 6;
            // 市内交通费在哪一列
            int targetLocalTransportationCellColumnNum = 7;

            // 这个正则要把目标内容里的数字取出来
            Pattern pattern = Pattern.compile("\\d+(\\.\\d+)?");

            double totalOtherFee = 0;
            double totalLocalFee = 0;
            for (int index = targetContentCellStartRowNum; index < end + 1; index++) {

                Cell cell = sheet.getRow(index).getCell(targetContentCellColumnNum);
                // 市内交通
                double cityTranFee = 0;
                /// 异地交通
                double bus = 0;
                if (cell == null) {
                    continue;
                }
                String cellString = cell.getStringCellValue();

                if (cellString != null && cellString.equals("")) {
                    Cell tempCell = sheet.getRow(index).getCell(0);
                    if (tempCell.getStringCellValue().contains("小计")) {
                        // 异地交通费 合计
                        Cell otherCell = sheet.getRow(index).getCell(3);
                        otherCell.setCellValue((totalOtherFee % 1 == 0) ? (int) totalOtherFee : totalOtherFee);
                        // 市内交通费 合计
                        Cell LocalCell = sheet.getRow(index).getCell(4);
                        LocalCell.setCellValue((totalLocalFee % 1 == 0) ? (int) totalLocalFee : totalLocalFee);
                        break;
                    }
                }
                if (cellString != null && cellString.length() > 0) {
                    if (cellString.contains(".5")) {
                        insertError("———————————————————————————");
                        insertError(cellString);
                    }


                    Matcher matcher = pattern.matcher(cellString);

                    while (matcher.find()) {
                        String matched = matcher.group();

                        double value = Double.parseDouble(matched);



                        if (value >= bigPrice) {

                            bus += value;
                        } else {
                            cityTranFee += value;
                        }


                    }

                    if (cellString.contains(".5")) {
                        insertError("异地交通费：" + bus);
                        insertError("市内交通费：" + cityTranFee);
                    }


                    totalOtherFee += bus;
                    totalLocalFee += cityTranFee;


                    sheet.getRow(index).getCell(targetOtherPlacesTransportationCellColumnNum).setCellValue((bus % 1 == 0) ? (int) bus : bus);
                    sheet.getRow(index).getCell(targetLocalTransportationCellColumnNum).setCellValue((cityTranFee));
                    if (index == targetContentCellStartRowNum) {
                        // 有时候起始的那一行写入不了数据，就再写一次
                        sheet.getRow(targetContentCellStartRowNum).getCell(targetOtherPlacesTransportationCellColumnNum).setCellValue((bus % 1 == 0) ? (int) bus : bus);
                        sheet.getRow(targetContentCellStartRowNum).getCell(targetLocalTransportationCellColumnNum).setCellValue(cityTranFee);
                    }
                }
            }
            insertLog("———————————————————————————");
            // 保存修改后的内容 到  saveFile
            FileOutputStream fos = new FileOutputStream(saveFile);
            insertSucess("尝试另存为文件");
            workbook.write(fos);
            fos.flush();
            fos.close();
            is.close();
            insertSucess("操作成功");
        } catch (IOException e) {
            insertError(e.getMessage());
//            Toast.makeText(MainActivity.this, e.getMessage() , Toast.LENGTH_SHORT).show();
        }

    }

    private void insertLog(String log) {
        insertString(log, Color.BLACK);
    }

    private void insertSucess(String log) {
        insertString(log, Color.BLUE);
    }

    private void insertError(String log) {
        insertString(log, Color.RED);
    }

    private void insertString(String redString, int stringColor) {
        //先得到TextView原有文本
        String originalString = logTextView.getText().toString() + "\n";


//将要添加的新字符串转化为SpannableString类型
        SpannableString spannableString = new SpannableString("\n" + redString);

//将SpannableString中的字体颜色设为红色
        spannableString.setSpan(new ForegroundColorSpan(stringColor), 0, spannableString.length(), 0);
// 由原始文本和新的SpannableString组合而成
        CharSequence finalText = TextUtils.concat(originalString, spannableString);
//将新SpannableString追加到TextView
        logTextView.append(spannableString);
    }
}